<script setup lang="jsx">
import { ref, onMounted, reactive, computed } from 'vue';
import { useEcharts } from '@/hooks/common/echarts';
import * as XLSX from 'xlsx';
import { message } from 'ant-design-vue';

// 生产趋势图表
const { domRef: productionTrendRef, updateOptions: updateProductionTrendOptions } = useEcharts(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['手机壳产量', '良品率'],
    top: 0,
    right: 10
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  },
  yAxis: [
    {
      type: 'value',
      name: '产量(件)',
      position: 'left'
    },
    {
      type: 'value',
      name: '良品率(%)',
      min: 0,
      max: 100,
      position: 'right'
    }
  ],
  series: [
    {
      name: '手机壳产量',
      type: 'line',
      stack: '总量',
      data: [5000, 132000, 101000, 134000, 150000, 180000, 210000, 150000, 180000, 160000, 190000, 210000],
      label: {
        show: true,
        position: 'top',
        fontSize: 9
      }
    },
    {
      name: '良品率',
      type: 'line',
      yAxisIndex: 1,
      data: [60.2, 70.1, 78.8, 95.5, 78.8, 97.2, 80.5, 80.8, 96.0, 96.3, 90.7, 97.0],
      label: {
        show: true,
        position: 'top',
        fontSize: 9,
        formatter: '{c}%'
      }
    }
  ]
}), false);

// 产品类型分布饼图
const { domRef: productTypeRef, updateOptions: updateProductTypeOptions } = useEcharts(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: '',
    left: 'right',
    top: 0,
    right: 10
  },
  series: [
    {
      name: '产品类型',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      padAngle: 5,
      itemStyle: {
        borderRadius: 10
      },
      label: {
        show: true,
        formatter: '{b|{b}}\n{per|{d}%}',
        rich: {
          b: {
            fontSize: 12,
            lineHeight: 20
          },
          per: {
            color: '#fff',
            backgroundColor: '#1F77B4',
            padding: [2, 4],
            borderRadius: 2,
          }
        }
      },
      labelLine: {
        show: true
      },
      data: [
        { value: 45, name: '硅胶手机壳' },
        { value: 25, name: 'PC塑料手机壳' },
        { value: 15, name: 'TPU软胶手机壳' },
        { value: 10, name: '皮革手机壳' },
        { value: 12, name: '金属手机壳' }
      ]
    }
  ]
}), false);

// 表格列定义 - 显示生产计划执行情况
const tableColumns = [
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 8
  },
  {
    key: 'productModel',
    dataIndex: 'productModel',
    title: '产品型号',
    width: 12
  },
  {
    key: 'productionQuantity',
    dataIndex: 'productionQuantity',
    title: '生产数量',
    width: 12
  },
  {
    key: 'qualifiedQuantity',
    dataIndex: 'qualifiedQuantity',
    title: '合格数量',
    width: 12
  },
  {
    key: 'defectiveQuantity',
    dataIndex: 'defectiveQuantity',
    title: '不良品数量',
    width: 12
  },
  {
    key: 'yieldRate',
    dataIndex: 'yieldRate',
    title: '良品率(%)',
    width: 12
  },
  {
    key: 'productionLine',
    dataIndex: 'productionLine',
    title: '生产线',
    width: 12
  },
  {
    key: 'productionDate',
    dataIndex: 'productionDate',
    title: '生产日期',
    width: 12
  },
  {
    key: 'manager',
    dataIndex: 'manager',
    title: '负责人',
    width: 8
  }
];

// 存储所有数据（包括原始数据和导入的数据）
const allTableData = ref([]);

// 生成写死的表格数据 - 制造业生产计划执行情况
const generateTableData = (page, pageSize) => {
  const productModels = ['iPhone 15 Pro', 'Samsung S24', 'Huawei P70', 'Xiaomi 14', 'OPPO Find X7', 'Vivo X100'];
  const productionLines = ['A生产线', 'B生产线', 'C生产线', 'D生产线', 'E生产线', 'F生产线'];
  const managers = ['张经理', '李主管', '王主任', '赵班长', '钱组长', '孙技术员'];

  const data = [];
  const totalItems = 1000; // 总共1000条数据

  // 根据页码和页面大小生成对应的数据
  const startIndex = (page - 1) * pageSize;
  const endIndex = Math.min(startIndex + pageSize, totalItems);

  for (let i = startIndex; i < endIndex; i++) {
    const randomModel = productModels[Math.floor(Math.random() * productModels.length)];
    const randomLine = productionLines[Math.floor(Math.random() * productionLines.length)];
    const randomManager = managers[Math.floor(Math.random() * managers.length)];

    // 随机生成生产数量(1000-5000)
    const productionQuantity = Math.floor(Math.random() * 4000) + 1000;

    // 随机生成良品率(90%-98%)
    const yieldRate = (Math.random() * 8 + 90).toFixed(2);

    // 计算合格数量和不良品数量
    const qualifiedQuantity = Math.floor(productionQuantity * yieldRate / 100);
    const defectiveQuantity = productionQuantity - qualifiedQuantity;

    // 生成随机日期(最近30天)
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 30);
    const randomDate = new Date(startDate.getTime() + Math.random() * (30 * 24 * 60 * 60 * 1000));
    const productionDate = randomDate.toLocaleDateString('zh-CN');

    data.push({
      key: i,
      index: i + 1,
      productModel: randomModel,
      productionQuantity: productionQuantity.toLocaleString(),
      qualifiedQuantity: qualifiedQuantity.toLocaleString(),
      defectiveQuantity: defectiveQuantity.toLocaleString(),
      yieldRate: yieldRate,
      productionLine: randomLine,
      productionDate,
      manager: randomManager
    });
  }
  return data;
};

// 更新当前页数据
const updateCurrentPageData = () => {
  const startIndex = (pagination.current - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  tableData.value = allTableData.value.slice(startIndex, endIndex);
};

// 获取行类名
const getRowClass = (index) => {
  return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
};

// 排序状态
const sortState = reactive({
  field: '',
  order: ''
});

// 处理排序
const handleSort = (field) => {
  // 如果点击的是当前排序字段，则切换排序方式
  if (sortState.field === field) {
    if (sortState.order === 'asc') {
      sortState.order = 'desc';
    } else if (sortState.order === 'desc') {
      sortState.order = '';
      sortState.field = '';
    } else {
      sortState.order = 'asc';
    }
  } else {
    // 点击新字段，默认升序
    sortState.field = field;
    sortState.order = 'asc';
  }
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 50,
  total: 1000,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
});

// 表格数据
const tableData = ref([]);

// 初始化数据
onMounted(() => {
  // 生成初始的1000条数据
  allTableData.value = [];
  for (let i = 0; i < 20; i++) { // 20页 * 50条 = 1000条
    const pageData = generateTableData(i + 1, 50);
    allTableData.value.push(...pageData);
  }
  updateCurrentPageData();

  // 确保图表正确初始化
  setTimeout(() => {
    updateProductionTrendOptions();
    updateProductTypeOptions();
  }, 100);
});

// 处理分页变化
const handlePageChange = (current, pageSize) => {
  pagination.current = current;
  pagination.pageSize = pageSize;
  updateCurrentPageData();

  // 重置排序状态
  sortState.field = '';
  sortState.order = '';
};

// 计算排序后的数据
const sortedTableData = computed(() => {
  if (!sortState.field || !sortState.order) {
    return tableData.value;
  }

  // 创建数据副本以避免修改原始数据
  const sortedData = [...tableData.value];

  return sortedData.sort((a, b) => {
    // 特殊处理日期字段排序
    if (sortState.field === 'productionDate') {
      // 将日期字符串转换为Date对象进行比较
      const dateA = new Date(a[sortState.field]);
      const dateB = new Date(b[sortState.field]);

      if (dateA < dateB) {
        return sortState.order === 'asc' ? -1 : 1;
      } else if (dateA > dateB) {
        return sortState.order === 'asc' ? 1 : -1;
      }
      return 0;
    }

    let aValue = a[sortState.field];
    let bValue = b[sortState.field];

    // 去除千位分隔符
    if (typeof aValue === 'string') {
      aValue = aValue.replace(/,/g, '');
    }
    if (typeof bValue === 'string') {
      bValue = bValue.replace(/,/g, '');
    }

    // 尝试转换为数字进行比较
    const numA = parseFloat(aValue);
    const numB = parseFloat(bValue);

    if (!isNaN(numA) && !isNaN(numB)) {
      aValue = numA;
      bValue = numB;
    }

    let result = 0;
    if (aValue < bValue) {
      result = -1;
    } else if (aValue > bValue) {
      result = 1;
    }

    return sortState.order === 'asc' ? result : -result;
  });
});

// 文件输入引用
const fileInput = ref(null);

// 导出到Excel
const exportToExcel = () => {
  // 准备导出数据
  const exportData = tableData.value.map(item => {
    const exportItem = {};
    tableColumns.forEach(col => {
      exportItem[col.title] = item[col.dataIndex];
    });
    return exportItem;
  });

  // 创建工作簿
  const ws = XLSX.utils.json_to_sheet(exportData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '生产记录');

  // 导出文件
  XLSX.writeFile(wb, '生产记录.xlsx');
};

// 导入数据
const importFromExcel = () => {
  fileInput.value.click();
};

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet);
      console.log('读取的Excel数据:', jsonData);

      if (jsonData.length === 0) {
        message.warning('Excel文件中没有数据');
        return;
      }

      // 将导入的数据转换为表格所需格式
      const importedData = jsonData.map((item, index) => {
        // 获取Excel中的数据，支持多种可能的列名
        const productModel = item.productModel || item.产品型号 || item['产品型号'] || item['productModel'] || '';
        const productionQuantity = parseInt(item.productionQuantity || item.生产数量 || item['生产数量'] || item['productionQuantity'] || 0);
        const qualifiedQuantity = parseInt(item.qualifiedQuantity || item.合格数量 || item['合格数量'] || item['qualifiedQuantity'] || 0);
        const defectiveQuantity = parseInt(item.defectiveQuantity || item.不良品数量 || item['不良品数量'] || item['defectiveQuantity'] || 0);
        const yieldRate = parseFloat(item.yieldRate || item.良品率 || item['良品率'] || item['yieldRate'] || 0);
        const productionLine = item.productionLine || item.生产线 || item['生产线'] || item['productionLine'] || '';
        const productionDate = item.productionDate || item.生产日期 || item['生产日期'] || item['productionDate'] || '';
        const manager = item.manager || item.负责人 || item['负责人'] || item['manager'] || '';

        return {
          key: allTableData.value.length + index,
          index: allTableData.value.length + index + 1,
          productModel,
          productionQuantity: productionQuantity.toLocaleString(),
          qualifiedQuantity: qualifiedQuantity.toLocaleString(),
          defectiveQuantity: defectiveQuantity.toLocaleString(),
          yieldRate: yieldRate.toFixed(2),
          productionLine,
          productionDate,
          manager
        };
      });

      // 将导入的数据追加到所有数据中
      allTableData.value = [...allTableData.value, ...importedData];
      pagination.total = allTableData.value.length;

      // 更新当前页显示的数据
      updateCurrentPageData();

      console.log('导入的数据:', importedData);
      console.log('所有数据总数:', pagination.total);
      message.success(`成功导入 ${jsonData.length} 条数据，当前共 ${pagination.total} 条数据`);
    } catch (error) {
      console.error('导入失败:', error);
      message.error('导入失败: ' + error.message);
    } finally {
      // 清空文件输入
      event.target.value = '';
    }
  };
  reader.readAsArrayBuffer(file);
};
</script>

<template>
  <div class="manufacturing-chart-page h-screen flex flex-col">
    <!-- 图表区域 -->
    <div class="grid grid-cols-1 gap-10px md:grid-cols-2 flex-shrink-0" style="height: 35vh;  margin-top: 10px;">
      <!-- 生产趋势图 -->
      <div class="chart-card bg-white p-10px rounded-4px shadow-sm h-full flex flex-col">
        <div class="chart-title-wrapper">
          <div class="text-14px font-bold chart-title-text">生产趋势</div>
        </div>
        <div ref="productionTrendRef" class="flex-grow overflow-hidden"></div>
      </div>

      <!-- 产品类型分布 -->
      <div class="chart-card bg-white p-10px rounded-4px shadow-sm h-full flex flex-col">
        <div class="chart-title-wrapper">
          <div class="text-14px font-bold chart-title-text">产品类型分布</div>
        </div>
        <div ref="productTypeRef" class="flex-grow overflow-hidden"></div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="flex-grow overflow-hidden mt-8px">
      <div class="bg-white p-10px rounded-4px shadow-sm h-full flex flex-col">
        <div class="chart-title-wrapper" style="display: flex; justify-content: space-between; align-items: center;">
          <div class="text-14px font-bold chart-title-text">生产记录</div>
          <div style="margin-top: -10px;">
            <AButton type="primary" @click="exportToExcel" class="mr-2">导出Excel</AButton>
            <AButton @click="importFromExcel" class="mr-2">导入Excel</AButton>
          </div>
        </div>
        <div class="flex-grow overflow-hidden flex flex-col min-h-0">
          <!-- 替换 Table 组件为自定义表格 -->
          <div class="custom-table-wrapper flex-grow flex flex-col">
            <div class="table-container">
              <div class="table-header sticky top-0 z-10">
                <div class="table-row table-head">
                  <div
                    class="table-cell sortable"
                    v-for="col in tableColumns"
                    :key="col.key"
                    :style="{ width: col.width + '%' }"
                    @click="handleSort(col.key)"
                  >
                    {{ col.title }}
                    <span class="ml-1">
                      <span
                        class="cursor-pointer hover:text-gray-300"
                        :style="{ color: sortState.field === col.key && sortState.order === 'asc' ? '#fff' : '' }"
                      >↑</span>
                      <span
                        class="cursor-pointer hover:text-gray-300"
                        :style="{ color: sortState.field === col.key && sortState.order === 'desc' ? '#fff' : '' }"
                      >↓</span>
                    </span>
                  </div>
                </div>
              </div>
              <div class="table-body overflow-auto flex-grow">
                <div
                  class="table-row"
                  v-for="(row, index) in sortedTableData"
                  :key="row.key"
                  :class="getRowClass(index)"
                >
                  <div class="table-cell" v-for="col in tableColumns" :key="col.key" :style="{ width: col.width + '%' }">
                    <div class="cell-content">{{ row[col.dataIndex] }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="table-pagination">
            <div class="flex items-center">
              <input
                ref="fileInput"
                type="file"
                accept=".xlsx,.xls"
                @change="handleFileUpload"
                style="display: none;"
              />
            </div>
            <a-pagination
              v-model:current="pagination.current"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :show-size-changer="pagination.showSizeChanger"
              :page-size-options="pagination.pageSizeOptions"
              :show-quick-jumper="pagination.showQuickJumper"
              :show-total="pagination.showTotal"
              @change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.manufacturing-chart-page {
  background-color: #f5f5f5;
  padding: 0 10px;
  overflow: hidden;
}

.chart-card {
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

/* 图表标题样式容器 */
.chart-title-wrapper {
  margin: 0 -10px;
  padding: 0 10px 8px;
  position: relative;
}

.chart-title-wrapper::after {
  content: "";
  position: absolute;
  bottom: 8px;
  left: 0;
  width: 100%;
  height: 1px;
  background-color: #e8e8e8;
}

/* 表格标题样式 */
.bg-white.p-10px.rounded-4px.shadow-sm.h-full.flex.flex-col > .chart-title-wrapper {
  margin: 0 -10px 10px -10px;
}

/* 图表标题文字样式 */
.chart-title-text {
  padding-bottom: 8px;
}

/* 添加自定义表格样式 */
.custom-table-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.table-header {
  background-color: #1F77B4 !important;
  border-bottom: 1px solid #e8e8e8;
  flex-shrink: 0;
  display: flex;
  min-width: 100%;
}

.table-header .table-cell {
  color: white;
  font-weight: bold;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
}

.table-body {
  flex-grow: 1;
  overflow-y: auto;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  min-width: 100%;
}

.table-row:last-child {
  border-bottom: none;
}

.table-head {
  font-weight: bold;
}

.table-cell {
  padding: 4px 8px;
  border-right: 1px solid #e8e8e8;
  font-size: 13px;
  white-space: nowrap;
  color: #333;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.table-cell:last-child {
  border-right: none;
}

.cell-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.table-row-even {
  background-color: white;
}

.table-row-odd {
  background-color: #EFF4F9;
}

.table-body .table-row:hover {
  background-color: #e6f7ff !important;
}

.table-pagination {
  margin-top: 6px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.surely-table-wrapper .surely-table-pagination) {
  margin: 8px 0 !important;
}
:deep(.table-card .ant-card-body) {
  padding-bottom: 10px !important;
}

/* 排序相关样式 */
.sortable {
  cursor: pointer;
  user-select: none;
}
</style>
